package com.appleyk.runnable;

import com.appleyk.bean.ZkApi1;
import com.appleyk.listener.ZkWatcher;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * <p></p>
 *
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @github https://github.com/kobeyk/dubbo-spring-boot-sample
 * @date created on 11:41 2020/11/23
 */
public class ZkConfigThread implements Runnable{

    private ZooKeeper zk;

    public ZkConfigThread(ZooKeeper zk){
        this.zk = zk;
    }

    private static final Logger logger = LoggerFactory.getLogger(ZkConfigThread.class);
    @Override

    public void run() {
        ZkWatcher watcher = new ZkWatcher();
        ZkApi1 zkApi = new ZkApi1(zk);
        String data = zkApi.getData("/db-config", watcher);
        logger.info(Thread.currentThread().getName()+"获取配置信息："+data);
        watcher.setData(data);
        watcher.setZk(zkApi);
    }

    public static void main(String[] args) throws InterruptedException{
        String connectString = "localhost:2181";
        int timeout = 4000;
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            // 连接成功后，会回调watcher监听，此连接操作是异步的，执行完new语句后，直接调用后续代码
            // 可指定多台服务地址 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
            ZooKeeper zooKeeper = new ZooKeeper(connectString, timeout, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if(Event.KeeperState.SyncConnected==event.getState()){
                        //如果收到了服务端的响应事件,连接成功
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            Thread t1 = new Thread(new ZkConfigThread(zooKeeper));
            Thread t2 = new Thread(new ZkConfigThread(zooKeeper));
            Thread t3 = new Thread(new ZkConfigThread(zooKeeper));
            Thread t4 = new Thread(new ZkConfigThread(zooKeeper));
            Thread t5 = new Thread(new ZkConfigThread(zooKeeper));
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
            // 阻塞主线程
            Thread.currentThread().join();
            logger.info("【初始化ZooKeeper连接状态....】={}",zooKeeper.getState());
        }catch (Exception e){
            logger.error("【初始化ZooKeeper连接异常....】={}",e);
        }
    }
}
